package model

import (
	"github.com/tianjigames/fairy/util"
	"github.com/topfreegames/pitaya/logger"
	"io/ioutil"
	"strings"
)

type (
	MapData struct {
		_LimitFlag []int
		_MapData [][]int
		M_nMapScale int
		M_MapTruckpath []*Pos
		M_nCX int
		M_nCZ int
	}

	moonDataStream struct {
		data []byte
		readIndex int
	}
)

func NewMapData() *MapData {
	return &MapData{
		_LimitFlag: make([]int,1),
	}
}

/**
加载地图
 */
func (p *MapData) LoadMap(fileName string) (bool,error) {
	 b,err := util.FileUtil.Exist(fileName)
	 if err != nil {
	 	logger.Log.Errorf("[MapData] LoadMap failed,error:%s",err.Error())
	 	return false,err
	 }

	 if b {
		data,err := ioutil.ReadFile(fileName)
		if err != nil {
			logger.Log.Errorf("[MapData] LoadMap failed,error:%s",err.Error())
			return false,err
		}

		pathData := moonDataStream{
			data: data,
		}

		//读取文件类型
		pathData.readMoonInt()
		//读取版本
		pathData.readMoonInt()

		p.M_nCX = pathData.readMoonInt() + 1
		p.M_nCZ = pathData.readIndex + 1
		p.M_nMapScale = pathData.readMoonInt()
		p._MapData = [][]int{{p.M_nCX,p.M_nCZ}}

		for i:=0;i<p.M_nCX;i++ {
			for j:=0;j<p.M_nCZ;j++ {
				p._MapData[i][j] = int(pathData.readByte())
			}
		}
	 }

	 fileName = strings.Replace(fileName,".path",".truck",1)
	 b,err = util.FileUtil.Exist(fileName)
	 if err != nil {
	 	logger.Log.Errorf("[MapData] LoadMap failed,error:%s",err.Error())
	 	return false,err
	 }

	 if b {
	 	var data []byte
	 	data,err = ioutil.ReadFile(fileName)
	 	if err != nil {
			logger.Log.Errorf("[MapData] LoadMap failed,error:%s",err.Error())
			return false,err
		}

		truckData := moonDataStream{
			data: data,
		}

		nPointCount := truckData.readMoonInt()
		if nPointCount > 0 {
			list := make([]*Pos,nPointCount)
			for i:=0;i<nPointCount;i++ {
				list[i] = NewPos(truckData.readMoonInt(),truckData.readMoonInt(),truckData.readMoonInt())
			}

			if list[len(list) - 1] != nil {
				p.M_MapTruckpath = list
			}
		}

	 }
	return true,nil
}

/**
读取一个整数
 */
func (p *moonDataStream) readMoonInt() int {
	b1 := p.data[p.readIndex]
	p.readIndex ++
	b2 := p.data[p.readIndex]
	p.readIndex ++
	b3 := p.data[p.readIndex]
	p.readIndex ++
	b4 := p.data[p.readIndex]
	p.readIndex ++

	return (int(b4) << 24) + (int(b3) << 16) + (int(b2) << 8) + int(b1)
}

func (p *moonDataStream) readByte() byte {
	ret := p.data[p.readIndex]
	p.readIndex ++
	return ret
}

